// pages/appeal/singleDynamic/index.js

const app = getApp()
import {
  appealToEndorse,
  appealToCancel
} from "../../../api/index"

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    data: {
      type: Object
    }
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {

    // 为诉求点赞
    appealEndorse: async function (e) {

      let appealId = e.currentTarget.dataset.id

      let data = {
        appealId: appealId,
      }

      let result = await appealToEndorse(data);

      if (result._id) {
        let dataList = this.data.data
        dataList.forEach((item, index) => {
          if (item._id == appealId) {
            dataList[index].isEndorse = true
            dataList[index].endorseCount = dataList[index].endorseCount + 1
          }
        })
        this.setData({
          data: dataList
        })
      } else {

        wx.showToast({
          title: '点赞失败',
          icon: 'none'
        })

      }





    },

    // 取消点赞
    cancelEndorse: async function (e) {

      let appealId = e.currentTarget.dataset.id
      let data = {
        appealId: appealId
      }

      let result = await appealToCancel(data);

      if (result.stats.removed > 0) {

        // 改变值
        let dataList = this.data.data
        dataList.forEach((item, index) => {
          if (item._id == appealId) {
            dataList[index].isEndorse = false
            dataList[index].endorseCount = dataList[index].endorseCount - 1
          }
        })
        this.setData({
          data: dataList
        })


      } else {

        wx.showToast({
          title: '取消失败',
          icon: 'none'
        })

      }





    },

    // 进入诉求详情
    gotoDetails(e) {

      let id = e.currentTarget.dataset.id

      wx.navigateTo({
        url: '/pages/appealDetails/appealDetails?appealId=' + id
      })

    },

    // 进入用户的页面
    gotoUserPage(e) {

      let userOpenid = e.currentTarget.dataset.openid

      let userInfo = wx.getStorageSync('wjUser')
      if (userInfo._openid && userInfo._openid === userOpenid) {

        wx.switchTab({
          url: '/pages/my/myProfile/myProfile',
        })

      } else {

        wx.navigateTo({
          url: '/pages/user/user?openid=' + userOpenid,
        })

      }

    }

  }
})